#include "performance_monitoring/getNpuStat.h"
namespace performance_monitoring{
	getNpuStat::getNpuStat() {
		std::cout << "__Cteate_getNpuStat__" << std::endl;
	};

	getNpuStat::~getNpuStat() {
		std::cout << "__Close_getNpuStat__" << std::endl;
	}

	void getNpuStat::get_npuocupy(NpuNode *npu) {
        char buff[BUFFSIZE];
        FILE* fd;
        fd = fopen("/proc/stat", "r");
        if (fd == NULL) {
            perror("open /proc/stat failed\n");
            exit(0);
        }
        fgets(buff, sizeof(buff), fd);
        sscanf(buff, "%s %u %u %u %u", npu->name, &npu->user, &npu->nice, &npu->system, &npu->idle);
        fclose(fd);
	}
    float getNpuStat::get_npu_usage() {
        get_npuocupy(&npu0);
        sleep(1);
        get_npuocupy(&npu1);
        float t1, t2;
        float id, sd;
        float cpu_used;

        t1 = (float)(npu0.user + npu0.nice + npu0.system + npu0.idle);
        t2 = (float)(npu1.user + npu1.nice + npu1.system + npu1.idle);

        id = (float)(npu1.user - npu0.user);
        sd = (float)(npu1.system - npu0.system);

        cpu_used = (100 * (id + sd) / (t2 - t1));
        return cpu_used;
    }


    float getNpuStat::get_mem_usage() {
        FILE* fd;
        fd = fopen("/proc/meminfo", "r");
        if (fd == NULL) {
            perror("open /proc/meminfo failed\n");
            exit(0);
        }
        size_t bytes_read;
        size_t read;
        char* line = NULL;
        int index = 0;
        int avimem = 0;
        int totalmem = 0;
        while ((read = getline(&line, &bytes_read, fd)) != -1) {
            if (strstr(line, "MemTotal") != NULL) {
                sscanf(line, "%*s%d%*s", &totalmem);
                index++;
                continue;
            }
            if (strstr(line, "MemAvailable") != NULL) {
                sscanf(line, "%*s%d%*s", &avimem);
                break;
            }
            index++;
        }
        int t = totalmem / 1024.0;
        int a = avimem / 1024.0;
        float mem = (t - a) * 100 / t;
        fclose(fd);
        return mem;
    }
    float getNpuStat::get_swap_usage() {
        std::cout << "[Error] /proc/swaps is no content,Return 0" << std::endl;
        return 0;
    }
}
